package com.matchmealpha;

import java.util.Scanner;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FindFriendsView extends LinearLayout implements OnClickListener {

	private TextView usernameText;
	private Button addRemoveButton;
	private String sessionid;
	RelativeLayout loadingPanel;

	public FindFriendsView(Context context, String str, String sessionid) {
		super(context);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.findfriends_item_view, this, true);

		this.usernameText = (TextView) this
				.findViewById(R.id.FindFriendsItemText);
		this.addRemoveButton = (Button) this
				.findViewById(R.id.FindFriendsItemButton);
		loadingPanel = (RelativeLayout) findViewById(R.id.friendListLoadingPanel);
		loadingPanel.setVisibility(View.GONE);

		setString(str);
		this.addRemoveButton.setOnClickListener(this);
		this.sessionid = sessionid;
	}

	public void setString(String str) {
		this.usernameText.setText(str);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case (R.id.FindFriendsItemButton):
			loadingPanel.setVisibility(View.VISIBLE);
			new RequestFriendTask().execute("");
			break;
		}
	}

	private class RequestFriendTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {

			HttpRequest req = new HttpRequest(sessionid);
			String response;
			response = req.sendPost(
					"https://matchmeapp.appspot.com/matchmeapp/request_friend/"
							+ usernameText.getText(), "");

			if (MatchMeTabWidget.REQUEST_SUCCESS.endsWith(response)) {
				return true;
			} else {
				return false;
			}
		}

		protected void onPostExecute(Boolean result) {
			loadingPanel.setVisibility(View.GONE);
			if (result) {
				addRemoveButton.setEnabled(false);
				addRemoveButton.setText("Pending....");
				usernameText.setTextColor(Color.GRAY);
			}

		}
	}
}
